package com.hw.protocol.tool.util;

import cn.hutool.core.util.ReflectUtil;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : lihy
 * @date : 2024/3/12 16:45
 * description:
 */
public class ModelUtil {

    public static void entity2Vo(Object entity, Object vo){
        List<Method> getMethodList = Arrays.stream(entity.getClass().getDeclaredMethods())
                .filter(method -> method.getName().startsWith("get"))
                .collect(Collectors.toList());
        for (Method getMethod : getMethodList) {
            try {
                Object value = getMethod.invoke(entity);
                Method setMethod = ReflectUtil.getMethodByName(vo.getClass(),
                        getMethod.getName().replace("get", "set"));
                if(value instanceof byte[]){
                    setMethod.invoke(vo, CrcUtil.bytesToHex((byte[])value, true));
                }else if(value instanceof Byte){
                    setMethod.invoke(vo, (Integer.toHexString(((Byte)value) & 0xFF)));
                }else{
                    setMethod.invoke(vo, value);
                }
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }
}
